#include<iostream>
#include<cstdlib>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string>
using namespace std;

int main()
{
    int fds[2];
    int n = pipe(fds);
    if(n<0)
    {
        std::cerr<<"pipe error"<<std::endl;
        return 1;
    }
    //创建子进程
    pid_t id = fork();//父进程的返回值是子进程的pid，而子进程是0
    if(id<0)
    {
        std::cerr<<"fork error"<<std::endl;
    }
    if(id==0)
    {//子进程
        close(fds[0]);//关闭读
        int cnt = 0;
        while(true)
        {
            
            std::string message = "hello bit,hello ";
            message+=(to_string(getpid()));
            message+=" cnt: ";
            message+=to_string(cnt);
            ::write(fds[1],message.c_str(),message.size());
            cnt++;
            sleep(1);
        }

        exit(0);
    }
    else
    {
        close(fds[1]);

        char buffer[1024];
        while(true)
        {
            int n = ::read(fds[0],buffer,sizeof(buffer));
            if(n>0)
            {
                buffer[n] = 0;
                std::cout<<"children read father "<<buffer<<std::endl;
            }
        }

        pid_t rid = waitpid(id,nullptr,0);
        std::cout<<"father wait children:"<<id <<"sucess"<<std::endl;
    }
    return 0;

}